package com.qianya.system.filter;

import cn.hutool.core.util.StrUtil;
import com.qianya.model.common.CommonResult;
import com.qianya.model.pojo.sys.qo.SysSetLimitIpQO;
import com.qianya.model.pojo.sys.vo.SysSetLimitIpVO;
import com.qianya.system.config.RedisUtil;
import com.qianya.system.feign.SystemManageFeign;
import com.qianya.util.BaseCommon;
import com.qianya.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

//import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 获取客户端的访问ip
 */
@Slf4j
@Component
public class IpFilter implements GlobalFilter, Ordered {
    @Autowired
    private SystemManageFeign systemManageService;
    //具体业务逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取客户端的访问ip
        ServerHttpRequest request = exchange.getRequest();
        String thisIp=this.getIpAddress(request);
        if (thisIp.equals("127.0.0.1")){
            return chain.filter(exchange);
        }
        List<SysSetLimitIpVO> limitIp=(List<SysSetLimitIpVO>)RedisUtil.get("ipLimit");
        for (int i = 0; i <limitIp.size() ; i++) {
            if (IPUtils.ipExistsInRange(thisIp,limitIp.get(i).getFiBegin(),limitIp.get(i).getFiEnd())){
                final ServerHttpResponse response = exchange.getResponse();
                byte[] bytes = "{\"code\":\"999\",\"message\":\"网站无法访问~~~~~~\"}".getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                return response.writeWith(Flux.just(buffer));//设置body
            }
        }
        log.info(thisIp+"--通过ip检查");
        //放行
        return chain.filter(exchange);
    }
    //过滤器的执行优先级,返回值越小,执行优先级越高
    @Override
    public int getOrder() {
        return 1;
    }
    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        if (StrUtil.isNotEmpty(ip) && ip .equals("0:0:0:0:0:0:0:1")){
            return "127.0.0.1";
        }
        return ip;
    }

}
